from django.shortcuts import render,redirect
from django import forms
from app02 import models
from django.conf import settings
from app02.utils.pegination import Pegination
from app02.utils.bootrsap import BootrsapForm,BootrsapModelForm


def city_list(request):
    if request.method=='GET':
        # 搜索框
        seach_list = {}
        seach_data = request.GET.get( 'q', '' )
        if seach_data:
            seach_list['name__contains'] = seach_data
        # 获取数据库中的信息
        data_list = models.City.objects.filter(**seach_list)
        print(data_list)
        # 分页
        page_object = Pegination( request, data_list )
        coxtent = {
            'page_string': page_object.html(),  # 生成页数据
            'seach_data':seach_data,  # 生成页码
            'data_list': page_object.page_mun

        }
        return render(request,'city_list.html',coxtent)

class CityModelForm(BootrsapModelForm):
    bootrsap_exitis_forms = ['img']
    class Meta:
        model=models.City
        fields='__all__'

def city_add(request):
    title='新增城市'
    if request.method=='GET':
        form=CityModelForm()
        return render(request,'city_edit.html',{'form':form,'title':title})
    form=CityModelForm(data=request.POST,files=request.FILES)
    if form.is_valid():
        form.save()
        return redirect('/city/list/')
    return render( request, 'city_edit.html', {'form': form, 'title': title} )


class CityEditModelForm(BootrsapModelForm):
    class Meta:
        model=models.City
        exclude=['img']

# 编辑城市列表
def city_edit(request,nid):
    title='编辑列表'
    row_i=models.City.objects.filter(id=nid).first()
    if request.method=='GET':
        # 将表中每一行数据，传给页面
        form=CityEditModelForm(instance=row_i)
        return render(request,'city_edit.html',{'form':form,'title':title})
    form=CityEditModelForm(data=request.POST,instance=row_i)
    if form.is_valid():
        form.save()
        return redirect('/city/list/')
    return render( request, 'city_edit.html', {'form': form, 'title': title} )

#删除城市
def city_delete(request,nid):
    models.City.objects.filter(id=nid).delete()
    return redirect('/city/list/')